package com.tos.second.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tos.second.service.BaiduAiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/baidu")
@CrossOrigin // 添加跨域支持
public class BaiduAiController {

    @Autowired
    private BaiduAiService baiduAiService;

    @PostMapping("/logo-detect")
    public ResponseEntity<Map<String, Object>> logoDetect(@RequestParam("image") MultipartFile image) {
        Map<String, Object> response = new HashMap<>();

        try {
            if (image == null || image.isEmpty()) {
                response.put("success", false);
                response.put("message", "上传的文件为空");
                return ResponseEntity.ok(response);
            }
            
            // 打印调试信息
            System.out.println("接收到图像文件: " + image.getOriginalFilename());
            System.out.println("文件大小: " + image.getSize() + " 字节");
            System.out.println("文件类型: " + image.getContentType());
            
            String result = baiduAiService.logoDetect(image);
            response.put("success", true);
            response.put("data", JSON.parseObject(result));
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "识别失败: " + e.getMessage());
            e.printStackTrace(); // 打印堆栈信息以便调试
        }

        return ResponseEntity.ok(response);
    }
    
    @PostMapping("/advanced-general")
    public String advancedGeneral(@RequestParam("image") MultipartFile image) {
        Map<String, Object> response = new HashMap<>();

        try {
            if (image == null || image.isEmpty()) {
                response.put("success", false);
                response.put("message", "上传的文件为空");
                return "上传的文件为空";
            }
            
            // 打印调试信息
            System.out.println("接收到图像文件: " + image.getOriginalFilename());
            System.out.println("文件大小: " + image.getSize() + " 字节");
            System.out.println("文件类型: " + image.getContentType());
            
            String result = baiduAiService.advancedGeneral(image);
            JSONObject jsonObject = JSON.parseObject(result);
            
            // 只提取分数最高的识别结果并转换为字符串
            String topResultString = "";
            if (jsonObject.containsKey("result") && jsonObject.getJSONArray("result").size() > 0) {
                JSONArray results = jsonObject.getJSONArray("result");
                JSONObject topResult = null;
                double highestScore = -1;
                
                // 查找分数最高的结果
                for (int i = 0; i < results.size(); i++) {
                    JSONObject item = results.getJSONObject(i);
                    if (item.containsKey("score")) {
                        double score = item.getDoubleValue("score");
                        if (score > highestScore) {
                            highestScore = score;
                            topResult = item;
                        }
                    }
                }
                
                // 将最高分结果转换为字符串
                if (topResult != null) {
                    topResultString = topResult.toJSONString();
                }
            }

            return topResultString;
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "识别失败: " + e.getMessage());
            e.printStackTrace(); // 打印堆栈信息以便调试
        }

        return "格式错误";
    }
    
    @PostMapping("/universal-classify")
    public ResponseEntity<Map<String, Object>> universalClassify(@RequestParam("image") MultipartFile image) {
        Map<String, Object> response = new HashMap<>();

        try {
            if (image == null || image.isEmpty()) {
                response.put("success", false);
                response.put("message", "上传的文件为空");
                return ResponseEntity.ok(response);
            }
            
            // 打印调试信息
            System.out.println("接收到图像文件: " + image.getOriginalFilename());
            System.out.println("文件大小: " + image.getSize() + " 字节");
            System.out.println("文件类型: " + image.getContentType());
            
            String result = baiduAiService.universalClassify(image);
            JSONObject jsonObject = JSON.parseObject(result);
            
            // 只提取分数最高的识别结果并转换为字符串
            String topResultString = "";
            if (jsonObject.containsKey("result") && jsonObject.getJSONArray("result").size() > 0) {
                JSONArray results = jsonObject.getJSONArray("result");
                JSONObject topResult = null;
                double highestScore = -1;
                
                // 查找分数最高的结果
                for (int i = 0; i < results.size(); i++) {
                    JSONObject item = results.getJSONObject(i);
                    if (item.containsKey("score")) {
                        double score = item.getDoubleValue("score");
                        if (score > highestScore) {
                            highestScore = score;
                            topResult = item;
                        }
                    }
                }
                
                // 将最高分结果转换为字符串
                if (topResult != null) {
                    topResultString = topResult.toJSONString();
                }
            }
            
            response.put("success", true);
            response.put("data", topResultString);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "识别失败: " + e.getMessage());
            e.printStackTrace(); // 打印堆栈信息以便调试
        }

        return ResponseEntity.ok(response);
    }
}